/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.contact;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.StringUtil;
import com.blandware.atleap.service.util.MailEngine;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.contact.ContactForm;
import com.blandware.atleap.webapp.util.core.GlobalProperties;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.RequestUtils;
import org.springframework.mail.MailPreparationException;
import org.springframework.mail.MailSendException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Sends message or forwards to action to preview message to be sent
 * </p>
 * <p><a href="PerformContactAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.14 $ $Date: 2006/08/03 10:07:45 $
 * @struts.action name="contactForm"
 * path="/contact/perform"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * @struts.action-forward name="inputForward"
 * path=".contact.contactPage"
 * @struts.action-forward name="contactSuccessful"
 * path="/contact/success.do"
 * redirect="true"
 * @struts.action-forward name="previewMessage"
 * path="/core/mailTemplate/previewMessage.do"
 * @struts.action-forward name="callContactPage"
 * path="/contact/callContactPage.do"
 * @struts.action-forward name="unsatisfiableNoReset"
 * path="/contact/callContactPage.do"
 */
public final class PerformContactAction extends BaseAction {

	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		if ( isCancelled(request) ) {
			return mapping.findForward("index");
		}

		ContactForm contactForm = (ContactForm) form;
		Map model = new HashMap();
		model.put("userName", contactForm.getUserName());
		model.put("email", contactForm.getEmail());
		model.put("message", StringUtil.elToBr(contactForm.getMessage()));

		String localeIdentifier = GlobalProperties.getInstance(request.getSession().getServletContext()).getString(Constants.CONTACT_LANGUAGE_PROPERTY);
		if ( GenericValidator.isBlankOrNull(localeIdentifier) ) {
			localeIdentifier = (RequestUtils.getUserLocale(request, null)).getLanguage();
		}

		if ( contactForm.getPreview() == null || !request.isUserInRole("core-mailTemplate-previewMessage") ) {

            resetToken(request);

			// send message
			MailEngine mailEngine = (MailEngine) getBean(Constants.MAIL_ENGINE_BEAN);
			String contactAddress = GlobalProperties.getInstance(request.getSession().getServletContext()).getString(Constants.CONTACT_ADDRESS_PROPERTY);
			try {
				mailEngine.sendMessage(contactAddress, "contactUs", localeIdentifier, model);
			} catch ( MailPreparationException e ) {
				if ( log.isErrorEnabled() ) {
					StringWriter sw = new StringWriter();
					e.printStackTrace(new PrintWriter(sw));
					log.error(sw.toString());
				}
				ActionMessages errors = new ActionMessages();
				errors.add("preparationFailed", new ActionMessage("contact.errors.preparationFailed"));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			} catch ( MailSendException e ) {
				if ( log.isErrorEnabled() ) {
					StringWriter sw = new StringWriter();
					e.printStackTrace(new PrintWriter(sw));
					log.error(sw.toString());
				}
				ActionMessages errors = new ActionMessages();
				errors.add("sendFailed", new ActionMessage("contact.errors.sendFailed"));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			} catch ( Exception e ) {
				if ( log.isErrorEnabled() ) {
					StringWriter sw = new StringWriter();
					e.printStackTrace(new PrintWriter(sw));
					log.error(sw.toString());
				}
				ActionMessages errors = new ActionMessages();
				errors.add("unknownError", new ActionMessage("contact.errors.unknownError"));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			}
			return mapping.findForward("contactSuccessful");
		} else {
			// forward to preview action
			request.setAttribute("identifier", "contactUs");
			request.setAttribute("model", model);
			request.setAttribute("locale", localeIdentifier);
			return mapping.findForward("previewMessage");
		}
	}

}